package com.itheima.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.mapper.AdminInfoMapper;
import com.itheima.mapper.AdminMapper;
import com.itheima.pojo.Admin;
import com.itheima.vo.AdminVo;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AdminService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static UUID UUID = null;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminInfoMapper adminInfoMapper;

    @Value("${jwt.secret}")
    private String secret;

    String r = "";

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param code
     */
    public String login(String username, String password, String code) {
        String redisKey = "TANHUA_USER_RANDON_" + UUID;
        if (redisTemplate.hasKey(redisKey)) {
            return null;
        }
        if (!code.equals(r)) {
            return null;
        }
        QueryWrapper<Admin> query = new QueryWrapper<>();
        query.eq("username", username);
        Admin admin = adminMapper.selectOne(query);

        if (null == admin) {
            return null;
        }

        if (username.equals(admin.getUsername()) && password.equals(admin.getPassword())) {
            //验证码在校验完成后，需要废弃
            this.redisTemplate.delete(redisKey);

            //生成token
            Map<String, Object> claims = new HashMap<String, Object>();
            claims.put("id", admin.getId());
            claims.put("username", admin.getUsername());

            // 生成token
            String token = Jwts.builder()
                    .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                    .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                    .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                    .compact();
            return token;

        }
        return null;
    }


    /**
     * 生成验证码
     *
     * @return
     */
    public String random() {

        UUID uuid = UUID.randomUUID();
        this.UUID = uuid;

        String key = "TANHUA_USER_RaANDON_" + uuid;
        //随机生成四位数字符串
        String random = null;
        random = String.valueOf(new Random().nextInt(9999 - 1000 + 1) + 1000);

        HashSet<String> set = new HashSet<>();

        while (set.contains(random)) {
            random = String.valueOf(new Random().nextInt(9999 - 1000 + 1) + 1000);
        }
        set.add(random);

        redisTemplate.opsForValue().set(key, random, 50, TimeUnit.MINUTES);

        long deadtime = System.currentTimeMillis() + 12000 * 1000;
        if (System.currentTimeMillis() == deadtime) {
            set.remove(random);
        }
        r = random;
        return random;
    }


    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public Admin queryUserByToken(String token) {
        try {
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();

            Admin admin = new Admin();
            admin.setId(Long.valueOf(body.get("id").toString()));
            return admin;
        } catch (ExpiredJwtException e) {
            log.info("token已经过期！ token = " + token);
        } catch (Exception e) {
            log.error("token不合法！ token = " + token, e);
        }
        return null;
    }

    /**
     * 获取用户信息
     *
     * @param token
     * @return
     */
    public AdminVo AdminInfo(String token) {
        Admin admin = queryUserByToken(token);

        QueryWrapper<Admin> query = new QueryWrapper<>();
        query.eq("id", admin.getId());
        Admin admin1 = adminMapper.selectOne(query);
        if (null == admin1) {
            return null;
        }
        AdminVo userVo = new AdminVo();
        userVo.setUid(String.valueOf(admin1.getId()));
        userVo.setUsername(admin1.getUsername());
        userVo.setAvatar(admin1.getAvatar());
        return userVo;

    }
}

